package com.jz.community.moduleshopping.refund.ui;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.donkingliang.imageselector.utils.ImageSelectorUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.ImageBrowserActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.utils.ArrayUtil;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.orderDetail.bean.OrderDetailBean;
import com.jz.community.moduleshopping.refund.adapter.ImagePickerAdapter;
import com.jz.community.moduleshopping.refund.adapter.RefundAdapter;
import com.jz.community.moduleshopping.refund.bean.UploadImageBean;
import com.jz.community.moduleshopping.refund.task.OrderUploadImageTask;
import com.jz.community.moduleshopping.refund.task.SubmitRefundTask;

import java.util.ArrayList;

import butterknife.BindView;
import io.github.rockerhieu.emojicon.EmojiconEditText;

public class RefundActivity extends BaseMvpActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {


    @BindView(R2.id.tv_back)
    ImageView tvBack;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.commit_order_toolbar)
    Toolbar commitOrderToolbar;
    @BindView(R2.id.ll_refund_indicator)
    LinearLayout llRefundIndicator;
    @BindView(R2.id.rv_refund_goods)
    RecyclerView rvRefundGoods;
    @BindView(R2.id.refund_edit)
    EmojiconEditText refundEdit;
    @BindView(R2.id.refund_edit_num)
    TextView refundEditNum;
    @BindView(R2.id.refund_img_rv)
    RecyclerView refundImgRv;
    @BindView(R2.id.ll_refund_data)
    LinearLayout llRefundData;
    @BindView(R2.id.button_refund_submit)
    Button buttonRefundSubmit;
    private RefundAdapter refundAdapter;
    private ImagePickerAdapter adapter_img;
    private final static int IMAGE_PICKER = 100;
    private int maxEditLength = 300;
    ArrayList<String> imagelist = new ArrayList<>();
    OrderDetailBean orderDetailBean;

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_refund;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this)
                .titleBar(commitOrderToolbar)
                .statusBarDarkFont(true, 0.2f)
                .init();
        tvTitle.setText("申请退款");

        orderDetailBean = (OrderDetailBean) getIntent().getSerializableExtra("orderDetailBean");

        View headView = LayoutInflater.from(mActivity).inflate(R.layout.module_shopping_refund_goods_head, (ViewGroup) rvRefundGoods.getParent(), false);
        rvRefundGoods.setLayoutManager(new LinearLayoutManager(this));

        refundAdapter = new RefundAdapter(R.layout.module_shopping_item_refund, new ArrayList<>());
        refundAdapter.addHeaderView(headView, 0);
        rvRefundGoods.setAdapter(refundAdapter);
        if (orderDetailBean != null) {
            refundAdapter.setNewData(orderDetailBean.getOrderItemList());
        }
        adapter_img = new ImagePickerAdapter(this, new ArrayList<>(), 8);
        adapter_img.setOnItemClickListener(this);
        refundImgRv.setLayoutManager(new GridLayoutManager(this, 3));
        refundImgRv.setNestedScrollingEnabled(true);
        refundImgRv.setHasFixedSize(true);
        refundImgRv.setAdapter(adapter_img);
    }

    @Override
    protected void addListener() {

        tvBack.setOnClickListener(view -> finish());
        refundEditNum.setText("0" + "/" + maxEditLength);
        refundEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = s.length();
                if (length <= maxEditLength) {
                    refundEditNum.setTextColor(getResources().getColor(R.color.font_gary_999));
                    refundEditNum.setText(length + "/" + maxEditLength);
                } else {
                    refundEditNum.setTextColor(getResources().getColor(R.color.home_red));
                    showNormal("最多输入" + maxEditLength + "字");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        buttonRefundSubmit.setOnClickListener(view -> {
            String content = refundEdit.getText().toString();
            if (adapter_img.getImages().size() > 0 && !TextUtils.isEmpty(content)) {
                uploadFile((ArrayList<String>) adapter_img.getImages());
            }
        });
    }


    private void uploadFile(ArrayList<String> list) {
        new OrderUploadImageTask(this, true, o -> {
            UploadImageBean bean = (UploadImageBean) o;
            if (!Preconditions.isNullOrEmpty(bean) && !Preconditions.isNullOrEmpty(bean.getData())) {
                submitRefund(ArrayUtil.listToString(bean.getData()));
            } else {
                WpToast.l(RefundActivity.this, "上传失败");
            }
        }).execute(list);
    }

    private void submitRefund(String imgs) {
        String content = refundEdit.getText().toString();
        new SubmitRefundTask(this, o -> {
            String code = (String) o;
            if (!TextUtils.isEmpty(code) && "200".equals(code)) {
                Intent intent = new Intent(RefundActivity.this, RefundDetailActivity.class);
                intent.putExtra("orderDetailBean", orderDetailBean);
                startActivity(intent);
                finish();
            } else {
                WpToast.l(RefundActivity.this, "提交失败");
            }
        }).execute(orderDetailBean.getOrderId(), content, imgs, orderDetailBean.getOrderItemList().get(0).getCurrentNums() + "");
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case -1:
                //打开选择,本次允许选择的数量
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .setMaxSelectCount(8)
                        .setViewImage(true) //是否点击放大图片查看,，默认为true
                        .start(this, IMAGE_PICKER); // 打开相册
                break;
            default:
                //打开预览
                Intent intent = new Intent(this, ImageBrowserActivity.class);
                intent.putStringArrayListExtra("Key_ImageList", imagelist);
                intent.putExtra("Key_CurrentPosition", position);
                intent.putExtra("isFromFile", 1);
                startActivity(intent);
                break;

        }
    }

    @Override
    public void onDeleteClick(View view, int position) {
        showDeleteDialog(position);
    }


    private void showDeleteDialog(final int position) {
        new MaterialDialog.Builder(mActivity)
                .title("提示")
                .content("是否确认删除图片?")
                .positiveText("确认")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    imagelist.remove(position);
                    adapter_img.setImages(imagelist);
                    dialog.dismiss();
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == IMAGE_PICKER) {
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
            imagelist.clear();
            imagelist.addAll(images);
            adapter_img.setImages(imagelist);
        }
    }
}
